<?php
class message extends base
{
	
	protected $_baseSetting = array();
	
	public function __construct()
    {
		parent::__construct();
		$this->_baseSetting = array('userid'=>MOBILEUSERID,'account'=>MOBILEACCOUNT,'password'=>MOBILEPASSWORD);
	}
	
	public function sendMessage()
	{
		$this->init_input();
		$senddata = $this->_baseSetting;
		$tel = $this->_checkMobileTel($this->input['tel']);
		if (!$tel) {
            return ;
        }
		$senddata['mobile'] = $tel;
		$senddata['content'] = $this->input['content'];
		$senddata['sendTime'] ='';
		$senddata['checkcontent'] = 0;
		$postdata = $this->_setPostData($senddata);
		$url = MOBILEURL.'/sms.aspx?action=send';
		$result = $this->_send($postdata, $url);
		return $result;
	}
	
	/**
	 * 
	 * 验证过滤电话号码
	 * @param int $tel
	 */
	private function _checkMobileTel($tel)
	{
		if(!$tel) return ;
		$tel = explode(',', $tel);
		$pattern = "/^(13[0-9]|15[0|1|2|3|5|6|7|8|9]|18[0|5|6|7|8|9])\d{8}$/";
		$source = array();
		foreach ($tel as $value)
		{
			preg_match($pattern, $value,$match);
			if($match && is_array($match)){
				$source[] = $match[0];
			}
		}
		$source = array_unique($source);
		return implode(',',$source);
	}
	/**
	 * 
	 * 查询余额
	 */
	public function overage()
	{
		$postdata = $this->_setPostData($this->_baseSetting);
		$url = MOBILEURL.'/sms.aspx?action=overage';
		$result = $this->_send($postdata,$url);
		$results = $this->xml_to_array($result);
		echo "<pre>";
		print_r($results);
	}
	
	/**
	 * 
	 * 发生请求
	 * @param unknown_type $data
	 * @param unknown_type $url
	 */
	private function _send($data,$url)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
		$result = curl_exec($ch);
		return $result;
	}
	
	/**
	 * 
	 * 构造请求数据
	 * @param unknown_type $postdata
	 */
	private function _setPostData($postdata)
	{
		if(!$postdata || !is_array($postdata)){
			return ;
		}
		$data = '';
		foreach ($postdata as $key=>$value){
			$data .="$key=".urlencode($value).'&';
		}
		return substr($data, 0,-1);
	}
}